//
// Created by lanlu on 2025/8/8.
//

#include <climits>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr){}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr){}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right){}
};

class Solution {
public:
    // 当确定了当前节点的值 也就划分出左右子树的值的范围
    // 左子树 [min, root->val]
    // 右子树 [root->val, max]
    bool isValidBST(TreeNode* root) {
        return isValidBSTByRec(root, LONG_MIN, LONG_MAX);
    }

    bool isValidBSTByRec(TreeNode * root, long min, long max)
    {
        // 空节点是满足的
        if (root == nullptr) return true;
        // 一旦发现不满足 返回false
        if (root -> val <= min || root -> val >= max)
        {
            return false;
        }

        // 当左右子树都满足时 才返回true
        bool left = isValidBSTByRec(root -> left, min, root -> val);
        bool right = isValidBSTByRec(root -> right, root -> val, max);
        return left && right;
    }
};